package org.jeecg.modules.demo.Kingdee.Job;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponseBody;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.DingTalk.MonthPayableOnoa.entity.MonthPayableOnoa;
import org.jeecg.modules.demo.DingTalk.MonthPayableOnoa.entity.MonthPayableOnoaItem;
import org.jeecg.modules.demo.DingTalk.MonthPayableOnoa.service.IMonthPayableOnoaItemService;
import org.jeecg.modules.demo.DingTalk.MonthPayableOnoa.service.IMonthPayableOnoaService;
import org.jeecg.modules.demo.util.DingTalkUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 检查钉钉审批实例状态的定时任务类
 * 
 * 功能：查询数据库中待审核的记录，根据实例ID获取钉钉审批状态，如果已审核则更新数据库记录
 * 
 * 工作流程：
 * 1. 查询数据库中状态为"待审核"的记录
 * 2. 遍历每条记录，根据实例ID调用钉钉接口获取审批状态
 * 3. 如果审批状态为"已审核"，则进一步检查供应商银行信息完整性
 * 4. 银行信息检查通过则更新数据库记录状态为"已审核"，否则更新为"已出错"
 * 
 * 银行信息检查不通过的情况：
 * - 供应商编号为空
 * - 未找到供应商银行信息
 * - 银行信息不完整（开户行、银行账号或户名任一为空）
 */
@Slf4j
@Component
public class CheckDingtalkApprovalStatusJob implements Job {

    @Autowired
    private IMonthPayableOnoaService monthPayableOnoaService;

    @Autowired
    private IMonthPayableOnoaItemService monthPayableOnoaItemService;

    @Autowired
    private DingTalkUtil dingTalkUtil;

    /**
     * 定时任务执行方法
     * 
     * @param jobExecutionContext 定时任务执行上下文
     * @throws Exception 执行过程中可能抛出的异常
     */
    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        try {
            log.info("开始执行钉钉审批状态检查任务");
            
            // 查询数据库中状态为"待审核"的记录
            List<MonthPayableOnoa> pendingRecords = monthPayableOnoaService.list(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MonthPayableOnoa>()
                    .ne("status", "已审核")
            );
            
            log.info("找到 {} 条待审核记录", pendingRecords.size());
            
            // 遍历每条记录，检查钉钉审批状态
            int updatedCount = 0;
            for (MonthPayableOnoa record : pendingRecords) {
                try {
                    String instanceId = record.getInstId();
                    if (instanceId != null && !instanceId.isEmpty()) {
                        // 调用钉钉接口获取审批实例详情
                        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult instanceDetail = 
                            dingTalkUtil.getOAInstDetail(instanceId);
                        
                        if (instanceDetail != null) {
                            String status = instanceDetail.getStatus();
                            String result = instanceDetail.getResult();
                            String businessId = instanceDetail.getBusinessId();
                            log.info("审批实例 {} 的状态为: {}", instanceId, status);
                            
                            // 如果状态为已审核，则更新数据库记录
                            if ("COMPLETED".equals(status)&& "agree".equals(result)) {
                                // 获取子表记录并检查供应商银行账号信息
                                List<MonthPayableOnoaItem> items = monthPayableOnoaItemService.selectByMainId(record.getId());
                                boolean hasError = false;
                                
                                // 初始化金蝶API
                                K3CloudApi api = new K3CloudApi();
                                
                                for (MonthPayableOnoaItem item : items) {
                                    // 根据供应商编号获取银行账号信息
                                    String supplierNo = item.getSupplierNo();
                                    String supplierName = item.getSupplier(); // 获取供应商名称
                                    if (supplierNo != null && !supplierNo.isEmpty()) {
                                        JSONObject bankInfo = getSupplierBankInfo(supplierNo, api);
                                        if (bankInfo == null) {
                                            log.error("供应商 {}({}) 未找到银行信息", supplierName, supplierNo);
                                            hasError = true;
                                            break;
                                        }
                                        // 检查银行信息是否完整
                                        String openBankName = bankInfo.getString("FOpenBankName");
                                        String bankCode = bankInfo.getString("FBankCode");
                                        String bankHolder = bankInfo.getString("FBankHolder");
                                        
                                        if (openBankName == null || openBankName.isEmpty() ||
                                            bankCode == null || bankCode.isEmpty() ||
                                            bankHolder == null || bankHolder.isEmpty()) {
                                            log.error("供应商 {}({}) 银行信息不完整: 开户行={}, 银行账号={}, 户名={}", 
                                                supplierName, supplierNo, openBankName, bankCode, bankHolder);
                                            hasError = true;
                                            break;
                                        }
                                    } else {
                                        log.error("供应商 {} 编号为空", supplierName);
                                        hasError = true;
                                        break;
                                    }
                                }
                                
                                if (hasError) {
                                    record.setStatus("已出错");
                                } else {
                                    record.setStatus("已审核");
                                }
                                record.setBillno(businessId);
                                monthPayableOnoaService.updateById(record);
                                updatedCount++;

                                log.info("已更新记录 {} 的状态为{}", record.getId(), hasError ? "已出错" : "已审核");
                            }
                        } else {
                            log.warn("未能获取审批实例 {} 的详情", instanceId);
                        }
                    } else {
                        log.warn("记录 {} 的实例ID为空", record.getId());
                    }
                } catch (Exception e) {
                    log.error("处理记录 {} 时发生错误: ", record.getId(), e);
                }
            }
            
            log.info("任务执行完成，共更新 {} 条记录", updatedCount);
            
        } catch (Exception e) {
            log.error("执行钉钉审批状态检查任务时发生错误: ", e);
        }
    }
    
    /**
     * 根据供应商编号获取供应商银行信息
     * 
     * @param supplierNo 供应商编号
     * @param api 金蝶API实例
     * @return 供应商银行信息
     */
    private JSONObject getSupplierBankInfo(String supplierNo, K3CloudApi api) {
        try {
            // 构造查询条件
            String filterString = "FNumber = '" + supplierNo + "'";
            String fieldKeys = "FOpenBankName,FBankCode,FBankHolder";
            
            // 构造查询JSON
            String queryJson = String.format(
                "{\"FormId\":\"BD_Supplier\",\"FieldKeys\":\"%s\",\"FilterString\":\"%s\",\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":1}",
                fieldKeys, filterString
            );
            
            log.info("开始查询供应商银行信息，查询条件: {}", filterString);
            
            // 执行查询
            String resultStr = api.billQuery(queryJson);
            
            // 解析查询结果
            List<JSONObject> resultList = JSONArray.parseArray(resultStr, JSONObject.class);
            
            if (!resultList.isEmpty()) {
                JSONObject item = resultList.get(0);
                log.info("查询到供应商 {} 的银行信息", supplierNo);
                return item;
            } else {
                log.warn("未找到供应商 {} 的银行信息", supplierNo);
                return null;
            }
        } catch (Exception e) {
            log.error("查询供应商 {} 的银行信息时发生错误: ", supplierNo, e);
            return null;
        }
    }
}